package scenic.testspring;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.Test;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by scenic on 2017/11/9.
 */
public class ClassPathXmlApplicationContext implements BeanFactory {

    private Map<String ,Object> beans = new HashMap<>();

    public ClassPathXmlApplicationContext(){
        try {
            init("beans.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void init(String fileName) throws Exception{

        SAXBuilder sb = new SAXBuilder();
        Document document = sb.build(getClass().getClassLoader().getResourceAsStream(fileName));
        Element rootElement = document.getRootElement();
        System.out.println(document);
        List<Element> beansList = rootElement.getChildren("bean");
        beansList.forEach(element -> {
            String id = element.getAttributeValue("id");
            String clazz = element.getAttributeValue("class");
            System.out.println( id + "　" + clazz);
            try {
                beans.put(id,  Class.forName(clazz).newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public Object getBean(String name) {
        return beans.get(name);
    }
}
